<template>
    <view class="container">
        <!-- 状态栏占位 -->
        <view class="status-bar" :style="{ height: `${systemInfo?.statusBarHeight}px` }" />
        <view class="header">
            
            <!-- 搜索栏 -->
            <view class="search-bar-wrapper" :style="searchBarStyle">
                <!-- 返回按钮 -->
                <view class="back-btn" @click="goBack">
                    <wd-icon name="arrow-left" size="18" />
                </view>
                <!-- 搜索框 -->
                <view class="search-bar" @click="goToSearch">
                    <wd-search
                        v-model="searchValue"
                        placeholder="搜索商品"
                        background="#f7f8fa"
                        readonly
                        disabled
                        use-action-slot
                    />
                </view>
            </view>

            <!-- 筛选栏 -->
            <view class="filter-bar" :style="{ transform: `translateY(${isFilterBarHidden ? '-100%' : '0'})` }">
                <!-- 综合下拉菜单 -->
                <view class="filter-dropdown" @click="showSortDropdown = !showSortDropdown">
                    <view class="filter-item" :class="{ active: sortType !== 'salesDesc' }">
                        <text>{{ getSortLabel }}</text>
                        <wd-icon :name="showSortDropdown ? 'up' : 'down'" size="14" />
                    </view>
                    <!-- 下拉菜单内容 -->
                    <view class="dropdown-content" v-if="showSortDropdown">
                        <view class="dropdown-item" 
                              v-for="option in sortOptions" 
                              :key="option.value"
                              :class="{ active: sortType === option.value }"
                              @click="handleSortSelect(option.value)">
                            {{ option.label }}
                        </view>
                    </view>
                </view>
                
                <!-- 销量选项 -->
                <view class="filter-item" 
                      @click="handleFilter('salesDesc')" 
                      :class="{ active: sortType === 'salesDesc' }">
                    <text>销量</text>
                </view>
                
                <!-- 筛选按钮 -->
                <view class="filter-item" @click="showFilterPopup = true">
                    <text>筛选</text>
                    <wd-icon name="filter" size="14" />
                </view>
            </view>
        </view>

        <!-- 商品列表 -->
        <scroll-view 
            scroll-y 
            class="goods-list" 
            @scrolltolower="loadMore" 
            refresher-enabled
            :refresher-triggered="isRefreshing" 
            :show-scrollbar="false"
            @scroll="handleScroll"
            @refresherrefresh="onRefresh">
            <!-- 商品保真提示 -->
            <view class="guarantee-tip">
                <wd-icon name="shield" size="14" color="#07c160" />
                <text>商品保真</text>
            </view>
            <view class="goods-list-container">
                <view class="goods-item" v-for="item in goodsList" :key="item.id" @click="goToDetail(item.id)">
                    <image :src="item.image" mode="aspectFill" class="goods-image" />
                    <view class="goods-info">
                        <view class="goods-header">
                            <view class="goods-title">{{ item.title }}</view>
                        </view>
                        <view class="goods-params">
                            <view class="param-list">
                                <view v-for="(param, index) in (item.parameters || []).slice(0, 3)" :key="index"
                                    class="param-item">
                                    <view class="param-value"
                                        :class="{ highlight: isHighlightParam(param.split('：')[0]) }">
                                        {{ param.split('：')[1] }}
                                    </view>
                                    <view class="param-label">{{ param.split('：')[0] }}</view>
                                </view>
                            </view>
                        </view>
                        <view class="price-section">
                            <view class="price-info">
                                <view class="price-wrapper">
                                    <text class="symbol">¥</text>
                                    <text class="amount">{{ formatPrice(item.price) }}</text>
                                </view>
                                <text v-if="item.price !== item.originalPrice" class="discount-tag">优惠价</text>
                                <text class="sales">{{ item.sales }}人付款</text>
                            </view>
                        </view>
                        <!-- 优惠券信息 -->
                        <view class="coupon-section" v-if="item.coupons && item.coupons.length">
                            <view class="coupon-list">
                                <!-- 展示前两张优惠券 -->
                                <view class="coupon-tag" v-for="coupon in item.coupons.slice(0, 2)"
                                    :key="coupon.id">
                                    <wd-icon name="coupon" size="12" class="coupon-icon" />
                                    <text class="tag-text">{{ coupon.text }}</text>
                                </view>
                                <!-- 如果超过两张，显示任选提示 -->
                                <text class="more-text" v-if="item.coupons.length > 2">{{ item.coupons.length
                                    }}张优惠券任选</text>
                            </view>
                        </view>
                    </view>
                </view>
            </view>

            <!-- 加载更多 -->
            <view class="loading-more" v-if="loading">
                <wd-loading type="spinner" />
                <text>加载中...</text>
            </view>
        </scroll-view>

        <!-- 筛选弹出层 -->
        <wd-popup v-model="showFilterPopup" position="bottom">
            <view class="filter-popup">
                <view class="popup-header">
                    <text class="title">筛选</text>
                    <wd-icon name="close" size="16" @click="showFilterPopup = false" />
                </view>

                <view class="filter-layout">
                    <!-- 左侧菜单 -->
                    <view class="filter-menu">
                        <view class="menu-item" 
                              :class="{ active: currentFilterIndex === 0 }" 
                              @click="handleMenuClick(0)">
                            商品分类
                        </view>
                        <view class="menu-item" 
                              :class="{ active: currentFilterIndex === 1 }" 
                              @click="handleMenuClick(1)">
                            品牌
                        </view>
                        
                        <!-- 动态筛选条件菜单项 -->
                        <view class="menu-item" 
                              v-for="(condition, index) in filterConditions" 
                              :key="condition.queryField"
                              :class="{ active: currentFilterIndex === index + 2 }" 
                              @click="handleMenuClick(index + 2)">
                            {{ condition.queryName }}
                        </view>
                    </view>

                    <!-- 右侧内容 -->
                    <scroll-view scroll-y class="filter-content" :scroll-top="scrollTop" @scroll="handleContentScroll"
                        :scroll-with-animation="true">
                        <!-- 分类列表 -->
                        <view id="section-category" class="content-section" :data-index="0">
                            <view class="section-title">商品分类</view>
                            <view class="tag-list">
                                <view class="tag-item"
                                    v-for="category in showAllCategories ? categoryList : categoryList.slice(0, 10)"
                                    :key="category.id"
                                    :class="{ active: selectedFilters['categoryId'] && selectedFilters['categoryId'][0] === category.id }"
                                    @click="toggleFilter('categoryId', category.id)">
                                    {{ category.name }}
                                </view>
                                <!-- 展示更多按钮 -->
                                <view class="show-more-btn" 
                                      v-if="categoryList.length > 10 && !showAllCategories"
                                      @click="showAllCategories = true">
                                    <text>展示更多</text>
                                    <wd-icon name="down" size="12" />
                                </view>
                            </view>
                        </view>

                        <!-- 品牌列表 -->
                        <view id="section-brand" class="content-section" :data-index="1">
                            <view class="section-title">品牌</view>
                            <view class="tag-list">
                                <view class="tag-item"
                                    v-for="brand in showAllBrands ? brandList : brandList.slice(0, 10)"
                                    :key="brand.id"
                                    :class="{ active: selectedFilters['brandId'] && selectedFilters['brandId'][0] === brand.id }"
                                    @click="toggleFilter('brandId', brand.id)">
                                    {{ brand.name }}
                                </view>
                                <!-- 展示更多按钮 -->
                                <view class="show-more-btn" 
                                      v-if="brandList.length > 10 && !showAllBrands"
                                      @click="showAllBrands = true">
                                    <text>展示更多</text>
                                    <wd-icon name="down" size="12" />
                                </view>
                            </view>
                        </view>

                        <!-- 动态渲染其他筛选条件 -->
                        <view v-for="(condition, index) in filterConditions" 
                              :key="condition.queryField"
                              :id="`section-${index + 2}`" 
                              class="content-section"
                              :data-index="index + 2">
                            <view class="section-title">{{ condition.queryName }}</view>
                            <view class="tag-list">
                                <view class="tag-item"
                                      v-for="value in condition.queryValue"
                                      :key="value"
                                      :class="{ active: selectedFilters[condition.queryField].includes(value) }"
                                      @click="toggleFilter(condition.queryField, value)">
                                    {{ value }}
                                </view>
                            </view>
                        </view>
                    </scroll-view>
                </view>

                <!-- 底部按钮 -->
                <view class="popup-footer">
                    <wd-button plain size="large" @click="resetFilter">重置</wd-button>
                    <wd-button type="primary" size="large" @click="applyFilter">确定</wd-button>
                </view>
            </view>
        </wd-popup>
    </view>
</template>

<script setup>
import { ref, nextTick, watch, computed, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { getProductList, getProductQueryConditions} from '@/api/product'
import { getBrandList } from '@/api/brand'
import { getCategoryList } from '@/api/category'
import { getSystemInfo } from '@/utils/system'
// 搜索
const searchValue = ref('')

// 筛选相关
const showFilterPopup = ref(false)
const sortType = ref('default')

// 筛选条件
const filterConditions = ref([])
// 选中的筛选值
const selectedFilters = ref({})

// 排序选项
const sortOptions = ref([
    { label: '综合', value: 'default' },
    { label: '价格从高到低', value: 'priceDesc' },
    { label: '价格从低到高', value: 'priceAsc' }
])

// 商品列表数据
const goodsList = ref([])

// 加载状态
const loading = ref(false)
const isRefreshing = ref(false)

// 筛选菜单
const currentFilterIndex = ref(0)

// 滚动位置
const scrollTop = ref(0)

// 分页参数
const current = ref(1)
const size = ref(5)
const hasMore = ref(true)

// 排序下拉菜单显示状态
const showSortDropdown = ref(false)

// 获取当前排序方式的显示文本
const getSortLabel = computed(() => {
    const option = sortOptions.value.find(opt => opt.value === sortType.value)
    return option ? option.label : '综合'
})

// 处理排序选择
const handleSortSelect = (value) => {
    sortType.value = value
    showSortDropdown.value = false
    loadData(true)
}

// 品牌列表
const brandList = ref([])
// 分类列表
const categoryList = ref([])
// 查询条件
const queryConditions = ref([])

// 添加展示更多的状态控制
const showAllCategories = ref(false)
const showAllBrands = ref(false)

// 获取系统信息
const systemInfo = ref(null)

// 获取筛选条件数据
const loadFilterData = async () => {
    try {
        // 获取查询条件
        const queryRes = await getProductQueryConditions()
        filterConditions.value = queryRes || []
        
        // 初始化选中的筛选值，包括分类和品牌
        selectedFilters.value = {
            categoryId: [],
            brandId: [],
            ...filterConditions.value.reduce((acc, condition) => {
                acc[condition.queryField] = []
                return acc
            }, {})
        }
        
        // 获取所有品牌列表
        const brandRes = await getBrandList({
            current: 1,
            size: 999 // 获取全部数据
        })
        brandList.value = brandRes.records || []
        
        // 获取所有分类列表
        const categoryRes = await getCategoryList({
            current: 1,
            size: 999 // 获取全部数据
        })
        categoryList.value = categoryRes.records || []
    } catch (error) {
        console.error('加载筛选数据失败:', error)
        uni.showToast({
            title: '加载筛选数据失败',
            icon: 'none'
        })
    }
}

// 格式化价格
const formatPrice = (price) => {
    if (!price && price !== 0) return ''
    // 转换为字符串并分割整数和小数部分
    const [integer, decimal] = price.toString().split('.')
    // 如果没有小数部分，直接返回整数
    if (!decimal) return integer
    // 如果小数部分全是0，返回整数部分
    if (decimal.replace(/0/g, '') === '') return integer
    // 去掉末尾的0
    const cleanDecimal = decimal.replace(/0+$/, '')
    // 如果去掉末尾的0后小数部分为空，返回整数
    if (!cleanDecimal) return integer
    // 否则返回带小数的数字
    return `${integer}.${cleanDecimal}`
}

// 处理筛选点击
const handleFilter = (type) => {
    sortType.value = type
    // 点击销量时发送请求
    if (type === 'salesDesc') {
        loadData(true)
    } else {
        loadData()
    }
}

// 重置筛选
const resetFilter = () => {
    // 重置所有筛选条件
    Object.keys(selectedFilters.value).forEach(key => {
        selectedFilters.value[key] = [] // 清空选中值
    })
    sortType.value = 'default'
}

// 加载数据
const loadData = async (isRefresh = false) => {
    if (isRefresh) {
        current.value = 1
        hasMore.value = true
        goodsList.value = []
    }

    if (!hasMore.value && !isRefresh) return

    loading.value = true
    try {
        const params = {
            current: current.value,
            size: size.value,
            fullQuery: searchValue.value || null,
            // 处理筛选条件
            ...Object.keys(selectedFilters.value).reduce((acc, key) => {
                if (selectedFilters.value[key].length > 0) {
                    // 直接使用第一个选中值
                    acc[key] = selectedFilters.value[key][0]
                }
                return acc
            }, {}),
            sortType: (() => {
                switch (sortType.value) {
                    case 'default': return 0
                    case 'priceDesc': return 1
                    case 'priceAsc': return 2
                    case 'salesDesc': return 3
                    default: return 0
                }
            })()
        }

        // 移除所有值为 null 的属性
        Object.keys(params).forEach(key => {
            if (params[key] === null || params[key] === undefined) {
                delete params[key]
            }
        })

        const res = await getProductList(params)

        const newList = res.records.map(item => ({
            id: item.id,
            title: item.name,
            price: item.price,
            sales: item.salesCount,
            image: item.mainImageUrl,
            tags: [], // 可以根据商品特性生成标签
            originalPrice: item.originalPrice,
            parameters: item.parameters || [],
            coupons: item.coupons?.map(coupon => ({
                id: coupon.id,
                text: coupon.name,
                isDefault: coupon.defaultUse
            })) || []
        }))

        if (isRefresh) {
            goodsList.value = newList
        } else {
            goodsList.value = [...goodsList.value, ...newList]
        }

        // 更新分页状态
        if (newList.length < size.value) {
            hasMore.value = false
        } else {
            current.value++
        }

    } catch (error) {
        console.error('加载数据失败:', error)
        uni.showToast({
            title: '加载失败',
            icon: 'none'
        })
    } finally {
        loading.value = false
        isRefreshing.value = false
    }
}

// 加载更多
const loadMore = () => {
    if (loading.value || !hasMore.value) return
    loadData()
}

// 下拉刷新
const onRefresh = async () => {
    isRefreshing.value = true
    await loadData(true)
}

// 跳转到详情页
const goToDetail = (id) => {
    uni.navigateTo({
        url: `/pages/product/detail?id=${id}`
    })
}

// 右侧滚动处理
const handleContentScroll = (e) => {
    const scrollTop = e.detail.scrollTop
    const query = uni.createSelectorQuery()
    query.selectAll('.content-section').boundingClientRect((rects) => {
        if (!rects || !rects.length) return

        const scrollViewQuery = uni.createSelectorQuery()
        scrollViewQuery.select('.filter-content').boundingClientRect((scrollViewRect) => {
            if (!scrollViewRect) return

            // 处理滚动到顶部的情况
            if (scrollTop <= 10) {
                currentFilterIndex.value = 0
                return
            }

            // 处理滚动到底部的情况
            const scrollHeight = e.detail.scrollHeight
            const clientHeight = scrollViewRect.height
            const isBottom = scrollTop + clientHeight >= scrollHeight - 10

            if (isBottom) {
                currentFilterIndex.value = filterConditions.value.length
                return
            }

            // 处理中间部分
            for (let i = 0; i < rects.length; i++) {
                const rect = rects[i]
                const rectTop = rect.top - scrollViewRect.top

                if (rectTop <= scrollViewRect.height * 0.5) {
                    currentFilterIndex.value = i
                }
            }
        }).exec()
    }).exec()
}

// 监听滚动位置变化
watch(scrollTop, (newVal) => {
    // 使用小程序原生的方法设置滚动位置
    const query = uni.createSelectorQuery()
    query.select('.filter-content').node((res) => {
        if (res && res.node) {
            res.node.scrollOffset({
                scrollTop: newVal,
                duration: 300
            })
        }
    }).exec()
})

// 点击左侧菜单时滚动到对应位置
const handleMenuClick = (index) => {
    currentFilterIndex.value = index

    // 获取目标section的位置并滚动
    const query = uni.createSelectorQuery()
    // 处理价格区间特殊情况
    const sectionId = index === filterConditions.value.length ? 'section-price' : `section-${index}`
    query.select(`#${sectionId}`).boundingClientRect((rect) => {
        if (!rect) return

        const scrollViewQuery = uni.createSelectorQuery()
        scrollViewQuery.select('.filter-content').boundingClientRect((scrollViewRect) => {
            if (!scrollViewRect) return

            let targetScrollTop

            // 处理第一个section
            if (index === 0) {
                targetScrollTop = 0
            }
            // 处理最后一个section
            else if (index === filterConditions.value.length) {
                targetScrollTop = 10000 // 确保滚动到底部
            }
            // 处理中间section
            else {
                targetScrollTop = rect.top - scrollViewRect.top + 50 // 稍微向上偏移一点
            }

            // 使用小程序原生的滚动方法
            uni.pageScrollTo({
                scrollTop: targetScrollTop,
                duration: 300
            })
        }).exec()
    }).exec()
}

// 应用筛选
const applyFilter = () => {
    showFilterPopup.value = false
    loadData(true)
}

// 搜索值变化时重新加载
watch(searchValue, (newVal) => {
    if (newVal !== undefined) {
        loadData(true)
    }
})

// 判断是否需要高亮显示的参数
const isHighlightParam = (paramName) => {
    const highlightParams = ['能效等级', '节能等级', '能耗等级']
    return highlightParams.includes(paramName)
}

// 切换筛选条件选择
const toggleFilter = (field, value) => {
    // 单选模式
    selectedFilters.value[field] = [value]
}

// 页面加载时初始化
onLoad(async (options) => {
    systemInfo.value = getSystemInfo()
    
    // 处理搜索参数
    if (options.fullQuery) {
        searchValue.value = decodeURIComponent(options.fullQuery)
    }

    await loadFilterData() // 先加载筛选数据

    // 处理分类参数
    if (options.categoryId) {
        selectedFilters.value.categoryId = [options.categoryId]
    }

    // 处理品牌参数
    if (options.brandId) {
        selectedFilters.value.brandId = [options.brandId]
    }

    loadData(true) // 最后加载商品数据
})

// 计算搜索栏样式
const searchBarStyle = computed(() => {
    if (!systemInfo.value?.menuButtonRect) return {}
    
    const { menuButtonRect } = systemInfo.value
    return {
        position: 'fixed',
        top: `${menuButtonRect.top}px`,
        left: '24rpx',
        height: `${menuButtonRect.height}px`,
        right: '24rpx',
        zIndex: 100,
        display: 'flex',
        alignItems: 'center',
        gap: '8rpx'
    }
})

// 在搜索框点击时跳转到搜索页
const goToSearch = () => {
    uni.navigateTo({
        url: '/pages/search/index'
    })
}

// 添加返回方法
const goBack = () => {
    uni.navigateBack({
        delta: 1
    })
}

// 添加筛选栏隐藏状态
const isFilterBarHidden = ref(false)
let lastScrollTop = 0

// 处理滚动事件
const handleScroll = (e) => {
    const scrollTop = e.detail.scrollTop
    // 向下滚动超过50px时隐藏筛选栏
    if (scrollTop > lastScrollTop && scrollTop > 50) {
        isFilterBarHidden.value = true
    } else if (scrollTop < lastScrollTop) {
        isFilterBarHidden.value = false
    }
    lastScrollTop = scrollTop
}
</script>

<style lang="scss" scoped>
.container {
    min-height: 100vh;
    background: #fff;
    display: flex;
    flex-direction: column;
    height: 100vh;
    box-sizing: border-box;
}

.status-bar {
    background: #fff;
    width: 100%;
    flex-shrink: 0;
}

.header {
    position: relative;
    z-index: 1;
    background: #fff;
    flex-shrink: 0;
    padding-top: v-bind('(systemInfo?.menuButtonRect?.height || 0) + (systemInfo?.menuButtonRect?.top || 0) - (systemInfo?.statusBarHeight || 0) + "px"');
    padding-bottom: 20rpx;
}

.search-bar-wrapper {
    display: flex;
    align-items: center;
    gap: 8rpx;
    background: #fff;
}

.back-btn {
    width: 48rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    
    &:active {
        opacity: 0.7;
    }
}

.search-bar {
    flex: 1;
    margin-right: v-bind('`${systemInfo?.menuButtonRect?.width || 0}px`');
    background: #fff;
    box-sizing: border-box;
    display: flex;
    align-items: center;

    :deep(.wd-search) {
        flex: 1;
        height: 100%;
        
        .wd-search__inner {
            height: 100%;
            display: flex;
            align-items: center;
            border-radius: 32rpx;
            padding: 0 16rpx;
        }

        .wd-search__input {
            font-size: 28rpx;
            pointer-events: none;
        }

        .wd-search__cancel {
            display: none;
        }
    }
}

.filter-bar {
    display: flex;
    background: #fff;
    padding: 12rpx 0;
    border-bottom: 1rpx solid #eee;
    transition: transform 0.3s ease-out;
    position: absolute;
    left: 0;
    right: 0;
    top: 100%;
    z-index: 1;
}

.filter-item {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 8rpx;
    font-size: 26rpx;
    color: #333;
    padding: 12rpx 0;

    &.active {
        color: #ff5500;
        font-weight: 500;
    }
}

.goods-list {
    flex: 1;
    overflow: hidden;
    margin-top: v-bind('isFilterBarHidden ? 0 : "88rpx"');  // 88rpx 是筛选栏的高度，根据实际调整
    transition: margin-top 0.3s ease-out;
}

.goods-list-container {
    padding: 0 24rpx;
    padding-bottom: 24rpx;
}

.goods-item {
    display: flex;
    padding: 1rpx 0;
    margin-bottom: 20rpx;
    align-items: flex-start;
    height: 280rpx;
    background: #fff;
}

.goods-image {
    width: 260rpx;
    height: 260rpx;
    border-radius: 12rpx;
    background: #f5f5f5;
    flex-shrink: 0;
    margin-right: 24rpx;
}

.goods-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-width: 0;
    height: 260rpx;
    /* 与图片等高 */
    position: relative;
    /* 添加相对定位 */
}

.goods-header {
    display: flex;
    flex-direction: column;
    margin-bottom: 16rpx;
    min-height: 84rpx;
    /* 固定标题高度，确保两行 */
}

.goods-title {
    font-size: 30rpx;
    color: #333;
    font-weight: 500;
    line-height: 1.4;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    overflow: hidden;
}

.goods-params {
    padding: 4rpx 0;
    height: 60rpx;
    /* 固定参数区域高度 */
}

.param-list {
    display: flex;
    align-items: center;
    gap: 20rpx;
    flex-wrap: nowrap;
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
    scrollbar-width: none;
    padding: 4rpx 0;

    &::-webkit-scrollbar {
        display: none;
    }
}

.param-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 2rpx;
}

.param-value {
    font-size: 24rpx;
    color: #333;
    line-height: 1.2;

    &.highlight {
        color: #07c160;
        font-weight: 500;
    }
}

.param-label {
    font-size: 20rpx;
    color: #999;
    line-height: 1.2;
}

.separator {
    color: #ddd;
    font-size: 20rpx;
    align-self: center;
}

.price-section {
    position: absolute;
    bottom: 40rpx;
    left: 0;
    right: 0;
}

.price-info {
    display: flex;
    align-items: center;
    gap: 8rpx;
    flex-wrap: nowrap;
}

.price-wrapper {
    display: inline-flex;
    align-items: baseline;
}

.symbol {
    font-size: 24rpx;
    color: #ff5500;
    line-height: 1;
    margin-right: 2rpx;
}

.amount {
    font-size: 36rpx;
    font-weight: bold;
    color: #ff5500;
    line-height: 1;
}

.discount-tag {
    font-size: 22rpx;
    color: #ff5500;
    background: rgba(255, 85, 0, 0.1);
    padding: 2rpx 8rpx;
    border-radius: 4rpx;
    line-height: 1;
    transform: translateY(-2rpx);
}

.sales {
    font-size: 24rpx;
    color: #666;
    margin-left: 8rpx;
    line-height: 1;
}

.filter-popup {
    height: 85vh;
    background: #fff;
    border-radius: 20rpx 20rpx 0 0;
    display: flex;
    flex-direction: column;
}

.popup-header {
    padding: 30rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1rpx solid #f5f5f5;

    .title {
        font-size: 32rpx;
        font-weight: 500;
        color: #333;
    }
}

.filter-layout {
    display: flex;
    flex: 1;
    overflow: hidden;
}

.filter-menu {
    width: 200rpx;
    background: #f7f8fa;
    height: 100%;
    overflow-y: auto;

    .menu-item {
        padding: 30rpx 20rpx;
        font-size: 28rpx;
        color: #666;
        text-align: center;
        position: relative;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        max-width: 200rpx;

        &.active {
            color: #ff5500;
            background: #fff;
            font-weight: 500;

            &::before {
                content: '';
                position: absolute;
                left: 0;
                top: 50%;
                transform: translateY(-50%);
                width: 6rpx;
                height: 32rpx;
                background: #ff5500;
                border-radius: 0 4rpx 4rpx 0;
            }
        }
    }
}

.filter-content {
    flex: 1;
    background: #fff;
    height: 100%;
    overflow-y: auto;

    // 优化滚动体验
    scroll-behavior: smooth;
    -webkit-overflow-scrolling: touch;
}

.content-section {
    padding: 30rpx;
    min-height: 200rpx;

    .section-title {
        font-size: 28rpx;
        color: #333;
        font-weight: 500;
        margin-bottom: 24rpx;
        padding: 0 6rpx;
    }

    // 分类列表 - 每行两个
    &#section-category {
        .tag-item, .show-more-btn {
            min-width: calc((100% - 12rpx) / 2);
            max-width: calc((100% - 12rpx) / 2);
        }
    }

    // 品牌列表 - 每行三个
    &#section-brand {
        .tag-item, .show-more-btn {
            min-width: calc((100% - 24rpx) / 3);
            max-width: calc((100% - 24rpx) / 3);
        }
    }

    // 其他筛选条件 - 每行两个
    &:not(#section-category):not(#section-brand) {
        .tag-item {
            min-width: calc((100% - 12rpx) / 2);
            max-width: calc((100% - 12rpx) / 2);
        }
    }
}

.tag-list {
    display: flex;
    flex-wrap: wrap;
    gap: 12rpx;
    padding: 0 6rpx;

    // 基础样式
    .tag-item, .show-more-btn {
        padding: 16rpx 24rpx;
        font-size: 26rpx;
        color: #666;
        background: #f7f8fa;
        border-radius: 100rpx;
        transition: all 0.3s;
        flex: 1;
        text-align: center;
        box-sizing: border-box;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;

        &.active {
            color: #ff5500;
            background: rgba(255, 85, 0, 0.1);
            font-weight: 500;
        }

        &:active {
            opacity: 0.8;
        }
    }
}

.popup-footer {
    padding: 20rpx 30rpx;
    padding-bottom: constant(safe-area-inset-bottom);
    padding-bottom: env(safe-area-inset-bottom);
    border-top: 1rpx solid #f5f5f5;
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20rpx;
    background: #fff;
    position: relative; // 确保底部按钮不会被内容遮挡
    z-index: 1;
}

.loading-more {
    text-align: center;
    padding: 30rpx;
    color: #999;
    font-size: 24rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8rpx;
    width: 100%;
    position: relative;
}

.coupon-section {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
}

.coupon-list {
    display: flex;
    flex-wrap: nowrap;
    gap: 8rpx;
    align-items: center;
}

.coupon-tag {
    display: inline-flex;
    align-items: center;
    padding: 2rpx 8rpx;
    background: rgba(255, 85, 0, 0.05);
    border: 1px solid rgba(255, 85, 0, 0.15);
    border-radius: 4rpx;
    gap: 4rpx;
    flex-shrink: 0;

    .coupon-icon {
        color: #ff5500;
        font-size: 20rpx;
    }

    .tag-text {
        font-size: 20rpx;
        color: #ff5500;
        line-height: 1.2;
        max-width: 140rpx;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
}

.more-text {
    font-size: 20rpx;
    color: #999;
    line-height: 1.2;
    padding: 2rpx 0;
    margin-left: 4rpx;
}

.filter-dropdown {
    position: relative;
    flex: 1;
}

.dropdown-content {
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    background: #fff;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    z-index: 100;
    border-radius: 8rpx;
}

.dropdown-item {
    padding: 16rpx;
    font-size: 26rpx;
    color: #333;
    text-align: center;
    
    &.active {
        color: #ff5500;
        font-weight: 500;
    }
    
    &:active {
        background: #f5f5f5;
    }
}

.show-more-btn {
    padding: 16rpx 24rpx;
    flex: 1;
    min-width: calc((100% - 24rpx) / 3);
    max-width: calc((100% - 24rpx) / 3);
    font-size: 26rpx;
    color: #666;
    background: #f7f8fa;
    border-radius: 100rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 4rpx;
    cursor: pointer;
    transition: all 0.3s;
    box-sizing: border-box;
    
    &:active {
        opacity: 0.8;
    }
}

.guarantee-tip {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 4rpx;
    padding: 16rpx 0;
    background: #fff;
    border-bottom: 1rpx solid #f5f5f5;
    
    text {
        font-size: 24rpx;
        color: #07c160;
    }
}
</style>